<?php

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
#
#	FILE:			includes/users.php
#	FUNCTION:		User-related classes and functions
#	AUTHOR:			Cameron Morrow
#	CREATED:		26/07/2005
#
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

class User {

	# Properties
	var $logged_in = false;
	var $id;
	var $login_name;
	var $first_name;
	var $last_name;
	var $group;
	var $group_name;
	var $editable_groups;
	var $hub_page;
	var $password;
	var $permission;
	var $visited_pages;
	var $can_lock;
	var $can_approve;

	# Input expected from POST
	var $post_id = "loginid";
	var $post_password = "loginpassword";
	var $post_permission="loginpermission";

	# Logout from GET
	var $get_logout = "logout";

	/**
	 * User() instantiates the User object
	*/
	function User($id = "", $password = "") {

		# Global
		global $IS_AUTHORIZED;
		global $AUTHORIZATION_MESSAGE;
		global $PAGE_ID;
		global $PROJECT_CODE;

		# Set ID and Password
		$this -> id = $id;
		$this -> login_name = "";
		$this -> password = $password;
		$this -> permission="";
		$this -> group = "";
		$this -> group_name = "";
		$this -> editable_groups = array();
		$this -> hub_page = "";
		$this -> visited_pages = array();
		$this -> can_lock = 0;
		$this -> can_approve = 0;

		# Check if attempting to log in
		if ($this -> detectAttemptedLogIn()) {
			$LOGIN_SUCCESS = $this -> attemptLogIn();
			addMessage($LOGIN_SUCCESS[1], $LOGIN_SUCCESS[0] ? 4 : 1);
		}

		# Check if attempting to log out
		if ($this -> detectAttemptedLogOut()) {
			$LOGOUT_SUCCESS = $this -> attemptLogOut();
			addMessage($LOGOUT_SUCCESS[1], $LOGOUT_SUCCESS[0] ? 4 : 1);
		}

		# Check if logged in
		if ($this -> isSessionLoggedIn()) {

			# Set logged in
			$this -> logged_in = true;

			# Store this page in list of visited pages
			if (!isset($_SESSION[$PROJECT_CODE . "visited_pages"])) {
				$_SESSION[$PROJECT_CODE . "visited_pages"] = array();
			}
			$_SESSION[$PROJECT_CODE . "visited_pages"][] = $PAGE_ID;

			# Get data from Session
			$this -> getDataFromSession();
		} else {

			# Set logged in
			$this -> logged_in = false;
		}
	}

	/**
	 * detectAttemptedLogIn() detects an attempt to log in
	 *
	 * @return true if a login is being attempted
	*/
	function detectAttemptedLogIn() {

		return (@$_POST[$this -> post_id]);
	}

	/**
	 * attemptLogIn() attempts to log in the user
	 * Fails if user is already logged in
	 *
	 * @return an array containing the success of the operation as a boolean, and a message
	*/
	function attemptLogIn() {

		# Globals
		global $VALID_CHAR_LIST;
		global $PAGES;
		global $PAGE_ID;
		global $PROJECT_DB_TABLES;

		if ($this -> isSessionLoggedIn()) {

			# Update logged_in
			$this -> logged_in = true;
			
			# Return message
			return array(false, "<p>You are already logged in. Please log out before attempting to log in again.</p>");

		} else {

			# Update logged in
			$this -> logged_in = false;

			# Get username and password from POST
			//$this -> login_name = removeInvalidChars(@$_POST[$this -> post_id], $VALID_CHAR_LIST["namesupper"]);
			//$this -> password = removeInvalidChars(strtolower(@$_POST[$this -> post_password]), $VALID_CHAR_LIST["ids"]);
			$this -> login_name = $_POST[$this -> post_id];
			$this -> password = $_POST[$this -> post_password];

			# SQL
			$sql = "SELECT u_id, u_fname, u_login_name, u_password, u_lname, u_group, g_name, g_priviledges, g_homepage, g_can_lock, g_can_approve FROM " . $PROJECT_DB_TABLES["users"] . ", " . $PROJECT_DB_TABLES["groups"] . " WHERE u_login_name = '" . $this -> login_name . "' AND u_group = g_id";
			
			# Get record
			$result = getRecord($sql);
			
			# If a result returned
			if (count($result) == 1) {

				# Check password
				if ($result[0]["u_password"] == md5($this -> password)) {

					# Log In
					$this -> logIn($result[0]["u_id"], $result[0]["u_login_name"], $result[0]["u_fname"], $result[0]["u_lname"], $result[0]["u_group"], $result[0]["g_name"], $result[0]["g_priviledges"], $result[0]["g_homepage"], $result[0]["g_can_lock"], $result[0]["g_can_approve"]);

					# Check group that was logged in has access to this page
					$authorized_groups = $PAGES -> getAuthorizedGroups($PAGE_ID);
					# Authorized
					$usersGroup=explode(",",$result[0]["u_group"]);
					$authorized = (findArrayInArray($usersGroup, $authorized_groups) === false) ? false : true;
					
					# If authorized to view page...
					if ($authorized) {

						# Return OK
						if($result[0]["g_name"]=="Administrators" || $result[0]["g_name"]=="Developers"){
							return array(true, "<p>You have successfully logged into the <em>" . $result[0]["g_name"] . "</em> group.</p>");
						}
						else{
							return array(true, "<p>You have successfully logged into the <em>" ."Student". "</em> group.</p>");
						}

					} else {

						# Return OK, but not allowed
						return array(true, "<p>You have been logged in successfully, but you provided insufficient credentials to access this page.</p>");
					}

				# Wrong password
				} else {

					return array(false, "<p>Sorry, that password is incorrect. Please try again.</p>");
				}

			# No results = wrong username
			} else {

				return array(false, "<p>Sorry, that username was not found. Please try logging in again.</p>");
			}
		}	
	}
	
	/**
	* getLdapData() returns the user details from UQ database via LDAP
	*/
	function getLdapData($username='',$password=''){

		$ldapserver = 'ldap.uq.edu.au';
		
		$basedn = 'ou=student,ou=people,o=the university of queensland,c=au';

		$studentusername = $username;
		
		$studentpassword = $password;
		
		$ldapconn = ldap_connect($ldapserver);

		if ($ldapconn) {
			
			// 1st Bind - Anonymous Bind then locate the student's entry
			//            in the Directory.
			$ldapbind = ldap_bind($ldapconn);
		
			$searchfilter = "(uid=$studentusername)";
			$wantedattr = array("mail","dn");
		
			$sr = ldap_search($ldapconn, $basedn, $searchfilter, $wantedattr);
			$studententry = ldap_first_entry($ldapconn, $sr);
			$studentdn = ldap_get_dn($ldapconn, $studententry);
		
			// 2nd Bind - Authenticated Bind using the student's entry dn
			//            returned above and the password supplied by the student.
		
			$ldapbind = ldap_bind($ldapconn, $studentdn, $studentpassword);
		
			if ($ldapbind) {
				
				$wantedattr = array("classes","dn");
		
				$sr = ldap_search($ldapconn, $basedn, $searchfilter, $wantedattr);
				
				$studententry = ldap_first_entry($ldapconn, $sr);
		
				$classes = ldap_get_values($ldapconn, $studententry, "classes");
				
				return $classes;
				
			} 
			else {
				return "Authentication Failed!";
			}
		
		} 
		else {
			return "Unable to connect to LDAPServer";
		}
	}

	/**
	 * isSessionLoggedIn() checks if logged in already as a session variable
	*/
	function isSessionLoggedIn() {

		global $PROJECT_CODE;
		# Check session
		return isset($_SESSION[$PROJECT_CODE . "id"]);
	}


	/**
	 * logIn() logs a user in
	*/
	function logIn($user_id = "", $login_name = "", $first_name = "", $last_name = "", $group = "", $group_name = "", $editable_groups = "", $hub_page = "", $can_lock, $can_approve) {

		# Globals
		global $PROJECT_DB_TABLES;

		# Set logged in
		$this -> logged_in = true;

		# Set properties
		$this -> id = $user_id;
		$this -> login_name = $login_name;
		$this -> first_name = $first_name;
		$this -> last_name = $last_name;
		$this -> group = $group;
		$this -> group_name = $group_name;
		$this -> editable_groups = explode(",", $editable_groups);
		$this -> hub_page = $hub_page;
		$this -> can_lock = $can_lock;
		$this -> can_approve = $can_approve;

		# Update last log in
		executeSQLQuery("UPDATE " . $PROJECT_DB_TABLES["users"] . " SET u_isloggedin = 1, u_lastlogin = '" . getFullDate() . "' WHERE u_id = '" . $this -> id . "'");

		# Set timeout
		session_cache_expire(30);

		# Set Session variables
		$this -> updateSession();

		# Log
		addLog($this -> id, 0, 4, $login_name);
	}


	/**
	 * updateDataFromDatabase() updates the data for the user from the database
	*/
	function updateDataFromDatabase() {

		# Globals
		global $PROJECT_DB_TABLES;

		# SQL
		$sql = "SELECT u_id, u_login_name, u_fname, u_password, u_lname, u_group, g_name, g_priviledges, g_homepage, g_can_lock, g_can_approve FROM " . $PROJECT_DB_TABLES["users"] . ", " . $PROJECT_DB_TABLES["groups"] . " WHERE u_login_name = '" . $this -> getID() . "' AND u_group = g_id";

		# Get record
		$result = getRecord($sql);

		# If a result returned
		if (count($result) == 1) {

			# Set params
			$this -> id = $result[0]["u_id"];
			$this -> login_name = $result[0]["u_login_name"];
			$this -> first_name = $result[0]["u_fname"];
			$this -> last_name = $result[0]["u_lname"];
			$this -> group = $result[0]["u_group"];
			$this -> group_name = $result[0]["g_name"];
			$this -> editable_groups = explode(",", $result[0]["g_priviledges"]);
			$this -> hub_page = $result[0]["g_homepage"];
			$this -> can_lock = $result[0]["g_can_lock"];
			$this -> can_approve = $result[0]["g_can_approve"];

			# Update session
			$this -> updateSession();
		}
	}


	/**
	 * detectAttemptedLogOut() detects an attempt to log out
	*/
	function detectAttemptedLogOut() {

		# Return if the required GET var was passed
		return (@$_GET[$this -> get_logout]);
	}

	/**
	 * attemptLogOut() attempts to log out
	*/
	function attemptLogOut() {

		# Globals
		global $PROJECT_DB_TABLES;
		global $PROJECT_CODE;

		# Update database
		if (@$_SESSION[$PROJECT_CODE . "id"]) {
			executeSQLQuery("UPDATE " . $PROJECT_DB_TABLES["users"] . " SET u_isloggedin = 0 WHERE u_id = '" . $_SESSION[$PROJECT_CODE . "id"] . "'");
		}

		# Log
		if (@$_SESSION[$PROJECT_CODE . "id"]) {
			addLog($_SESSION[$PROJECT_CODE . "id"] . "|" . implode(",", $_SESSION[$PROJECT_CODE . "visited_pages"]), 1, 4, $_SESSION[$PROJECT_CODE . "id"]);
		}

		# Kill Session vars
		$_SESSION = array();

		# Wipe out Cookie
		if (isset($_COOKIE[session_name()])) {
		   setcookie(session_name(), "", time() - 42000, "/");
		}

		# Destroy
		session_destroy();

		# Unset vars
		$this -> logged_in = false;
		$this -> id = "";
		$this -> login_name = "";
		$this -> password = "";
		$this -> first_name = "";
		$this -> last_name = "";
		$this -> group = "";
		$this -> can_lock = 0;
		$this -> can_approve = 0;

		# Return
		return array(true, "<p>You were logged out successfully.</p>");
	}

	/**
	 * isUserAuthorized() returns whether a user is authorized to see a page with the passed group IDs
	*/
	function isUserAuthorized($group_id_array = array()) {
		$userGroup=explode(",",$this -> group);
		if (findArrayInArray($group_id_array, $userGroup) !== false) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * getDataFromSession() gets the data from the current session
	*/
	function getDataFromSession() {
	
		global $PROJECT_CODE;

		$this -> id = $_SESSION[$PROJECT_CODE . "id"];
		$this -> login_name = $_SESSION[$PROJECT_CODE . "login_name"];
		$this -> group = $_SESSION[$PROJECT_CODE . "group"];
		$this -> group_name = $_SESSION[$PROJECT_CODE . "group_name"];
		$this -> first_name = $_SESSION[$PROJECT_CODE . "first_name"];
		$this -> last_name = $_SESSION[$PROJECT_CODE . "last_name"];
		$this -> editable_groups = $_SESSION[$PROJECT_CODE . "editable_groups"];
		$this -> hub_page = $_SESSION[$PROJECT_CODE . "hub_page"];
		$this -> visited_pages = $_SESSION[$PROJECT_CODE . "visited_pages"];
		$this -> can_lock = $_SESSION[$PROJECT_CODE . "can_lock"];
		$this -> can_approve = $_SESSION[$PROJECT_CODE . "can_approve"];
	}

	/**
	 * updateSession() updates the Session variables based on the current User properties
	*/
	function updateSession() {
	
		global $PROJECT_CODE;

		# Set Session variables
		$_SESSION[$PROJECT_CODE . "id"] = $this -> id;
		$_SESSION[$PROJECT_CODE . "login_name"] = $this -> login_name;
		$_SESSION[$PROJECT_CODE . "group"] =  $this -> group;
		$_SESSION[$PROJECT_CODE . "group_name"] = $this -> group_name;
		$_SESSION[$PROJECT_CODE . "first_name"] = $this -> first_name;
		$_SESSION[$PROJECT_CODE . "last_name"] = $this -> last_name;
		$_SESSION[$PROJECT_CODE . "editable_groups"] = $this -> editable_groups;
		$_SESSION[$PROJECT_CODE . "hub_page"] = $this -> hub_page;
		$_SESSION[$PROJECT_CODE . "can_lock"] = $this -> can_lock;
		$_SESSION[$PROJECT_CODE . "can_approve"] = $this -> can_approve;
	}


	/**
	 * getIP() gets the IP address for this user
	*/
	function getIP() {
		return $_SERVER["REMOTE_ADDR"];
	}

	/**
	 * getPermission() gets the permission for the user
	 */
	function getPermission(){
		return $this->visited_pages;
	}
	
	/**
	 * getGroup() gets the group
	 *
	 * @return the group
	*/
	function getGroup() {
		return $this -> group;
	}
	
	/**
	 * IsNameInGroup() to check whether the given name is in this group list
	 *
	 * @param $groupName is name of a group
	 *
	 * @return true/false
	*/
	function IsNameInGroup($groupName = ""){
		
		global $PROJECT_DB_TABLES;
		
		$arrGroups = explode(",",$this -> group);
		
		$counter = 0;
		
		foreach($arrGroups as $itemGroups){
		
			$sql = "select g_name FROM ".$PROJECT_DB_TABLES['groups']." WHERE ";
			
			if($counter == 0){
			
				$sql .= "g_id ='".$itemGroups."' ";
			}
			else{
				
				$sql .= " OR g_id ='".$itemGroups."' ";
			}
		}

		$result = getRecord($sql);
		
		foreach($result as $itemResult){
			
			if($itemResult["g_name"] == $groupName){
				
				return true;
			}
		}
		
		return false;
	}


	/**
	 * getGroupName() gets the group name
	 *
	 * @return the group name
	*/
	function getGroupName() {
		return $this -> group_name;
	}


	/**
	 * getLoginName() gets the login name
	*/
	function getLoginName() {
		return $this -> login_name;
	}


	/**
	 * getEditableGroups() gets the editable groups
	 *
	 * @return the editable groups array
	*/
	function getEditableGroups() {
		return $this -> editable_groups;
	}


	/**
	 * setEditableGroups() sets the editable groups
	*/
	function setEditableGroups($editable_groups = array()) {

		# Store
		$this -> editable_groups = $editable_groups;

		# Update Session
		$this -> updateSession();

	}


	/**
	 * getHubPage() gets the hub page
	 *
	 * @return the hub page
	*/
	function getHubPage() {
		return $this -> hub_page;
	}
	
	
	/**
	 * getCanLock() gets whether the group can lock pages
	*/
	function getCanLock() {
		return $this -> can_lock;
	}
	
	
	/**
	 * getCanApprove() gets whether the group can approve pages
	*/
	function getCanApprove() {
		return $this -> can_approve;
	}


	/**
	 * getID() gets the ID
	 *
	 * @return the ID
	*/
	function getID() {
		return $this -> id;
	}

	/**
	 * getFirstName() gets the first name
	 *
	 * @return the first name
	*/
	function getFirstName() {
		return $this -> first_name;
	}

	/**
	 * getLastName() gets the last name
	 *
	 * @return the last name
	*/
	function getLastName() {
		return $this -> last_name;
	}


	/**
	 * getVisitedPages() gets the visited pages
	 *
	 * @return the visited pages
	*/
	function getVisitedPages() {
		return $this -> visited_pages;
	}

	/**
	 * isLoggedIn() returns whether the logged in var is set
	*/
	function isLoggedIn() {
		return $this -> logged_in;
	}

	/**
	 * generateLoginForm() generates the log in form
	 *
	 * @param login_message is the message to display to the user above the form
	 *
	 * @return the HTML ready to print
	*/
	function generateLoginForm($login_message = "<p>Please enter your user ID and password to continue:</p>") {

		# Global
		global $PAGE_ID;
		global $PAGES;
		global $PROJECT_TITLE;
		global $FORCE_LOGIN;
		
		if (@!$FORCE_LOGIN) {
			$FORCE_LOGIN = false;
		}

		# Header
		$output = "<div id=\"contentheader\">\n" .
			"<h2>Please enter your details for the " . $PROJECT_TITLE . " site:</h2>\n" .
			"</div>";

		# Suitable groups
		$output .= "<div id=\"accessgroups\"><p>This page can be accessed by:</p><ul>";
		foreach ($PAGES -> getAuthorizedGroupNames($PAGE_ID) as $authorized_page) {
			$output .= "<li>" . $authorized_page["name"] . "</li>";
		}
		$output .= "</ul></div>";


		# Open form
		$output .= "<div id=\"login\"><form name=\"loginform\" id=\"loginform\" action=\"" . $PAGE_ID . ".php" . ($FORCE_LOGIN ? "?forcelogin=true" : "") . "\" method=\"post\">";

		# Message
		$output .= $login_message;


		$output .= "<p><span id=\"useridspan\"><label for=\"loginid\"><strong>USER ID:</strong></label> <input type=\"text\" name=\"loginid\" id=\"loginid\" value=\"\" /></span> <span id=\"passwordspan\"><label for=\"loginpassword\"><strong>PASSWORD:</strong></label> <input type=\"password\" name=\"loginpassword\" id=\"loginpassword\" value=\"\" /></span><span id=\"loginbuttonspan\"><input type=\"submit\" value=\"GO\" class=\"button\" /></span></p>";//<input type=\"radio\" name=\"loginpermission\" id=\"loginpermission\" value=\"student\" checked=\"true\"/><label for=\"loginpermission\"><strong>Student</strong>

		# Close form
		$output .= "</form></div>";

		# Return
		return $output;
	}
	
	function generateAjaxLoginForm($login_message = "<p>Please enter your user ID and password to continue:</p>"){
		
		# Global
		global $PAGE_ID;
		global $PAGES;
		global $PROJECT_TITLE;
		global $FORCE_LOGIN;
		
		if (@!$FORCE_LOGIN) {
			$FORCE_LOGIN = false;
		}

		# Header
		$output = "<div id=\"contentheader\">\n" .
			"<h2>Please enter your details for the " . $PROJECT_TITLE . " site:</h2>\n" .
			"</div>";

		# Suitable groups
		$output .= "<div id=\"accessgroups\"><p>This page can be accessed by:</p><ul>";
		foreach ($PAGES -> getAuthorizedGroupNames($PAGE_ID) as $authorized_page) {
			$output .= "<li>" . $authorized_page["name"] . "</li>";
		}
		$output .= "</ul></div>";


		# Open form
		$output .= "<div id=\"login\"><form name=\"loginform\" id=\"loginform\" action=\"xml_editor.php" . ($FORCE_LOGIN ? "?forcelogin=true" : "") . "\" method=\"post\">";

		# Message
		$output .= $login_message;


		$output .= "<p><span id=\"useridspan\"><label for=\"loginid\"><strong>USER ID:</strong></label> <input type=\"text\" name=\"loginid\" id=\"loginid\" value=\"\" /></span> <span id=\"passwordspan\"><label for=\"loginpassword\"><strong>PASSWORD:</strong></label> <input type=\"password\" name=\"loginpassword\" id=\"loginpassword\" value=\"\" /></span><span id=\"loginbuttonspan\"><input type=\"submit\" value=\"GO\" class=\"button\" /></span></p>";//<input type=\"radio\" name=\"loginpermission\" id=\"loginpermission\" value=\"student\" checked=\"true\"/><label for=\"loginpermission\"><strong>Student</strong>

		# Close form
		$output .= "</form></div>";

		# Return
		return $output;
	}


	/**
	 * generateUnauthorizedMessage() generates an authorized message
	 *
	 * @return the message
	*/
	function generateUnauthorizedMessage() {

		# Globals
		global $PAGES;
		global $PAGE_ID;
		global $PROJECT_DB_TABLES;

		# Output
		$output = "<h2>You are not authorized</h2><p>Sorry, while you are logged in, you are not authorized to see this page.</p>";
		
		# Suitable groups
		$output .= "<p>The following groups have access to this page:</p><ul>";
		foreach ($PAGES -> getAuthorizedGroupNames($PAGE_ID) as $authorized_page) {
			$output .= "<li>" . $authorized_page["name"] . "</li>";
		}
		$output .= "</ul>";

		# Offer to log out
		$output .= "<p>If you believe you should be able to access this page, you can <a href=\"?logout=1\">log out</a> and try logging in under different credentials.</p>";

		# Hub Page section
		$hub_page_section = getRecord("SELECT p_section FROM " . $PROJECT_DB_TABLES["pages"] . " WHERE p_id = '" . $this -> hub_page . "'");

		# Hub page link
		if (count($hub_page_section) != 0) {
			$output .= "<p>Alternatively, you can proceed to the <a href=\"../" . $hub_page_section[0]["p_section"] . "/" . $this -> hub_page . ".php\">home page</a> for the <em>" . $this -> group_name . "</em> group.</p>";
		}

		# Return
		return $output;
	}
	/**
	*IsUserAuthorisedForLanguage() is the function to check whether current language is authorised for current user
	*
	*
	*/
	function IsUserAuthorisedForLanguage($language = ""){
		
		global $PROJECT_DB_TABLES;
		
		$array_group = explode(",",$this->group);
		
		$sql = "SELECT g_name from ".$PROJECT_DB_TABLES["groups"]." WHERE";
		
		$counter = 0;
		
		foreach($array_group as $item_group){
			
			if($counter == 0){
			
				$sql .=" g_id='".$item_group."' ";
			}
			else{
				
				$sql .=" OR g_id='".$item_group."' ";
			}
			
			$counter ++;
		}
		
		//return $sql;
		
		$result = getRecord($sql);
		
		foreach($result as $value){
			
			if($value['g_name'] == $language || $value['g_name'] == "Administrators" || $value['g_name'] == "Developers"){
				
				return true;
			}
		}
		
		return false;
	}
	
	/**
	*getUserGroups() will return the array of groups
	*
	*
	*/
	function getUserGroups(){
		
		global $PROJECT_DB_TABLES;
		
		$arrGroups = explode(",",$this -> group);
		
		$counter = 0;
		
		foreach($arrGroups as $itemGroups){
		
			$sql = "select g_name FROM ".$PROJECT_DB_TABLES['groups']." WHERE ";
			
			if($counter == 0){
			
				$sql .= "g_id ='".$itemGroups."' ";
			}
			else{
				
				$sql .= " OR g_id ='".$itemGroups."' ";
			}
		}

		$result = getRecord($sql);
		
		$groups = array();
		
		foreach($result as $itemResult){
			
			array_push($groups,$itemResult["g_name"]);

		}
		
		return $groups;
	}
	
}


/**
*getGroupIDByName() get the group id on the basis of namer
*@param $gName is the group name
*@return group id
*/
function getGroupIDByName($gName = ""){
	
	global $PROJECT_DB_TABLES;
	
	$sql = "SELECT g_id from ".$PROJECT_DB_TABLES["groups"]." WHERE g_name = '".$gName."'";
	
	$result = getRecord($sql);
	
	if(count($result) != 0){
		
		return $result[0]["g_id"];
	}
	
	return "";
}


?>